import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/wx_pay_info_entity.dart';
import 'package:factoryside/generated/json/wx_pay_info_entity_helper.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/my_number_textInputFormatter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:tobias/tobias.dart';

///充值页面

class RechargePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _RechargeState();
  }
}

class _RechargeState extends State<RechargePage> {
  String recharge;
  var values=[100,300,500,1000,2000,3000];
  int selectIndex=-1;
  TextEditingController rechargeCtr=TextEditingController();

  bool _alipaySelected = true;
  bool _wxSelected = false;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initFluwx();
  }
  _initFluwx() async {
    await registerWxApi(
        appId: "wxd22da3eb42259071",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://your.univerallink.com/link/");
    var result = await isWeChatInstalled;
    print("is installed $result");
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: buildAppBar('充值',null,context),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
//                Container(
//                  color: Colors.white,
//                  child: GridView(
//                    gridDelegate:
//                    SliverGridDelegateWithFixedCrossAxisCount(
//                        crossAxisCount: 3,
//                        mainAxisSpacing: 5.0,
//                        crossAxisSpacing: 5.0,
//                        childAspectRatio: 1.5),
//                    children: values
//                        .asMap().keys.map((index) => InkWell(
//                      onTap: (){
//                        selectIndex=index;
//                        rechargeCtr.text='${values[index]}';
//                        rechargeCtr.selection =
//                            TextSelection.fromPosition(
//                                TextPosition(offset: rechargeCtr.text.length));
//                        setState(() {
//
//                        });
//                      },
//                      child: Container(
//                        decoration: BoxDecoration(
//                            color: selectIndex==index?Colors.blue:Colors.white,
//                            border: Border.all(width: selectIndex==index?0:1.5,color: Colors.grey),
//                            borderRadius: BorderRadius.all(
//                                Radius.circular(5))),
//                        width: double.infinity,
//                        height: 50,
//                        margin: EdgeInsets.all(10),
//                        child: Center(child: Text(
//                          '${values[index]}',
//                          textAlign: TextAlign.center,
//                          style: TextStyle(fontWeight: FontWeight.bold,color: selectIndex==index?Colors.white:Colors.black),
//                        ),),
//                      ),
//                    ))
//                        .toList(),
//                    physics: NeverScrollableScrollPhysics(), //禁止滚动
//                    shrinkWrap: true,
//                  ),
//                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.only(left: 10),
                  padding: EdgeInsets.all(10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
//                      Text('充值金额',style: TextStyle(color: Colors.grey,fontSize: 18),),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 20),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text('¥',style: TextStyle(fontWeight: FontWeight.bold,color: Colors.black,fontSize: 28),),
                            SizedBox(width: 20,),
                            Expanded(child: Container(
                                height: 40,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                ),
                                child: TextField(
                                  controller: rechargeCtr,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(fontSize: 28,fontWeight: FontWeight.normal, color: Colors.black),
                                  maxLines: 1,
                                  maxLength: 6,
                                  keyboardType: TextInputType.numberWithOptions(decimal: true),
//                                  inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                                  inputFormatters: [MyNumberTextInputFormatter(digit: 2)],
                                  decoration: InputDecoration(
                                    hintText: '输入金额',
                                    counterText: "", //此处控制最大字符是否显示
                                    border: InputBorder.none,
                                    contentPadding: EdgeInsets.symmetric(vertical: 0),
                                  ),
                                ))),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.symmetric(vertical: 10),
                  child: Column(
                    children: [
                      InkWell(
                        onTap: () {
                          setState(() {
                            _alipaySelected = true;
                            _wxSelected = false;
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 20, vertical: 20),
                          child: Row(
                            children: [
                              Image.asset(
                                _alipaySelected
                                    ? 'assets/checked.png'
                                    : 'assets/unchecked.png',
                                width: 15,
                                height: 15,
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 10),
                                child: Image.asset(
                                  'assets/zhifubao.png',
                                  width: 25,
                                  height: 25,
                                ),
                              ),
                              Container(
                                  margin:
                                  EdgeInsets.symmetric(horizontal: 10),
                                  child: Text('支付宝'))
                            ],
                          ),
                        ),
                      ),
                      Divider(height: 1,),
                      InkWell(
                        onTap: () {
                          setState(() {
                            _alipaySelected = false;
                            _wxSelected = true;
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 20, vertical: 20),
                          child: Row(
                            children: [
                              Image.asset(
                                _wxSelected
                                    ? 'assets/checked.png'
                                    : 'assets/unchecked.png',
                                width: 15,
                                height: 15,
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 10),
                                child: Image.asset(
                                  'assets/weixinzhifu.png',
                                  width: 25,
                                  height: 25,
                                ),
                              ),
                              Expanded(
                                child: Container(
                                    margin: EdgeInsets.symmetric(
                                        horizontal: 10),
                                    child: Text('微信')),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 30),
                  child: Column(
                    children: [
                      Container(
                        color: Colors.transparent,
                        width: double.infinity,
                        height: 50,
                        margin: EdgeInsets.all(10),
                        child: RaisedButton(
                          onPressed: () {
                            recharge=rechargeCtr.text;
                            if(recharge.isEmpty){
                              showToast( '请输入充值金额');
                              return;
                            }
                            if(_alipaySelected){
                              _alipay(context);
                            }else{
                              wxpay();
                            }
                          },
                          child: Text(
                            '充值',
                            style: TextStyle(color: Colors.white,fontSize: 18),
                          ),
                          color: ColorsUtil.hexToColor(Api.btnColor),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),

        ],
      ),
    );
  }

  /// 选择支付方式
  Future<int> _showChoosePayWay() {
    return showModalBottomSheet<int>(
      context: context,
      builder: (BuildContext context) {
        return Container(
          margin: EdgeInsets.all(10),
          height: 120,
          child: Column(
            children: [
              ListTile(
                title: Center(child: Text("支付宝")),
                onTap: () async {
                  Navigator.of(context).pop();
                  _alipay(context);
                },
              ),
              ListTile(
                title: Center(child: Text("微信")),
                onTap: () async {
                  Navigator.of(context).pop();
                  wxpay();
                },
              ),
            ],
          ),
        );
      },
      elevation: 10,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(10), topRight: Radius.circular(10))),
    );
  }

  void wxpay() {
    isWeChatInstalled.then((value){
      if(!value){
        RequestUtil.post(Api.getWXOrderStr,{
          'UserID': Api.userName,
          'BisId' : '',
          'OrderId' : '',
          'TotalAmount' : recharge,
          'Type' : 1,
          'Style' : 'worker',
          'JsonStr' : ''
        }).then((value){
          WxPayInfoDataItem2 payInfo=wxPayInfoDataItem2FromJson(WxPayInfoDataItem2(), value['Data']['Item2']);
          payWithWeChat(
            appId: payInfo.appid,
            partnerId: payInfo.partnerid,
            prepayId: payInfo.prepayid,
            packageValue: payInfo.package,
            nonceStr: payInfo.noncestr,
            timeStamp: int.parse(payInfo.timestamp),
            sign: payInfo.sign,
          ).then((value){
            if(value){
    //                                    Navigator.pop(context,'充值成功');
            }else{
              showToast( '充值失败');
            }
          });
        });
      }else{
        showToast( '请安装微信APP');
      }
    });
  }

  void _alipay(BuildContext context) {
    isAliPayInstalled().then((data){
      if(!data){
        RequestUtil.post(Api.getOrderStr,{
          'UserID': Api.userName,
          'BisId' : '',
          'OrderId' : '',
          'TotalAmount' : recharge,
          'Type' : 1,
          'Style' : 'worker',
          'JsonStr' : ''
        }).then((value){
          aliPay(value['Data']['Item2']).then((value){
    //                                  {
    //                                    result: partner="2088411752388544"&seller_id="etongka123@163.com"&out_trade_no="180926084213001"&subject="test pay"&total_fee="0.01"&notify_url="http://127.0.0.1/alipay001"&service="mobile.securitypay.pay"&payment_type="1"&_input_charset="utf-8"&it_b_pay="30m"&return_url="m.alipay.com"&success="true"&sign_type="RSA"&sign="nCZ8MDhsNvYNAbrLZJZ2VUy6vydgAp+JCq1aQo6ORDYtI9zwtnja3qNGQNiDJCuktoIj7fSTM487XhjPDqnOreZjIA1GJpxu9D1I3nMXIn1M7DfZ0noDwXcYZ438/jbYac7g8mhpwdKGweLCAni9mO3Y6q3iBFkox8i9PcsGxJY=",
    //                                    resultStatus: 9000,
    //                                    memo: ,
    //                                    platform:iOS
    //                                  }
            if(value['resultStatus']==9000){
              Navigator.pop(context,'充值成功');
            }else{
              showToast( '充值失败');
            }
          });
        });
      }else{
        showToast( '请安装支付宝APP');
      }
    });
  }
}
